import { Button, Card, Drawer, Form, Input, Select, Space, Tag, TreeSelect } from "antd";
import Table, { type ColumnsType } from "antd/es/table";

import orgService from "@/api/services/system/orgService";
import userService from "@/api/services/system/userService";
import { TableToolbar } from "@/components/grid/TableToolbar";
import { t } from "@/locales/i18n";
import { formatDate } from "@fullcalendar/core/index.js";
import { message } from "antd";
import { useEffect, useMemo, useState } from "react";
import type { Organization, UserInfo } from "#/entity";
import { BasicStatus } from "#/enum";

export default function UserPage() {
	const [loading, setLoading] = useState(false);
	const [queryParams, setQueryParams] = useState({
		account: "",
		name: "",
		status: "",
		page: 1,
		pageSize: 10,
	});
	const [total, setTotal] = useState(0);
	const [list, setList] = useState<UserInfo[]>([]);
	const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
	const [tableSize, setTableSize] = useState<"large" | "middle" | "small">("middle");
	const [drawerVisible, setDrawerVisible] = useState(false);
	const [editingUser, setEditingUser] = useState<UserInfo | null>(null);
	const [form] = Form.useForm();
	const [isView, setIsView] = useState(true); // 控制表单禁用状态
	const [resetPasswordVisible, setResetPasswordVisible] = useState(false);
	const [resetPasswordForm] = Form.useForm();
	const [orgTree, setOrgTree] = useState<Organization[]>([]); // 添加组织机构树状态

	// 定义表格列
	const columns: ColumnsType<UserInfo> = [
		{
			title: "账号",
			key: "account",
			dataIndex: "account",
			width: 120,
		},
		{
			title: "姓名",
			key: "name",
			dataIndex: "name",
			align: "center",
			width: 120,
		},
		{
			title: "部门",
			key: "orgName",
			dataIndex: "orgName",
			align: "center",
		},
		{
			title: "性别",
			key: "gender",
			dataIndex: "gender",
			align: "center",
			width: 120,
		},
		{
			title: "手机号",
			key: "phone",
			dataIndex: "phone",
			align: "center",
			width: 120,
		},
		{
			title: "邮箱",
			key: "email",
			dataIndex: "email",
			align: "center",
			width: 120,
		},
		{
			title: "状态",
			key: "status",
			dataIndex: "status",
			align: "center",
			width: 120,
			render: (status) => (
				<Tag color={status === BasicStatus.DISABLE ? "error" : "success"}>
					{status === BasicStatus.DISABLE ? "失效" : "有效"}
				</Tag>
			),
		},
		{
			title: "创建时间",
			key: "createTime",
			dataIndex: "createTime",
			align: "center",
			width: 120,
			render: (time) => formatDate(time, { locale: "zh-cn" }),
		},
		{
			title: "操作",
			key: "operation",
			align: "center",
			width: 100,
			render: (_, record) => (
				<Space>
					<Button type="link" onClick={() => handleView(record)}>
						{t("common.view")}
					</Button>
					<Button type="link" onClick={() => handleEdit(record)}>
						{t("common.edit")}
					</Button>
				</Space>
			),
		},
	];

	// 状态管理
	const [selectedValues, setSelectedValues] = useState<string[]>(() =>
		columns.filter((col) => col.key !== "operation").map((col) => String(col.key!)),
	);

	// 处理过滤后的列配置
	const filteredColumns = useMemo(() => {
		return [
			// 显示选中的列
			...columns.filter(
				(col) => selectedValues.includes(String(col.key)) || col.key === "operation", // 始终包含操作列
			),
		].sort((a, b) => {
			// 保持原始顺序
			const originalIndex = columns.findIndex((c) => c.key === a.key);
			const targetIndex = columns.findIndex((c) => c.key === b.key);
			return originalIndex - targetIndex;
		});
	}, [selectedValues]);

	const fetchUserList = async () => {
		try {
			setLoading(true);
			const res = await userService.pageList({
				account: queryParams.account,
				name: queryParams.name,
				status: queryParams.status,
				page: queryParams.page,
				pageSize: queryParams.pageSize,
			});
			setList(res.records);
			setTotal(res.total);
		} catch (error) {
			console.error("获取用户列表失败:", error);
		} finally {
			setLoading(false);
		}
	};

	// 获取组织机构树数据
	const fetchOrgTree = async () => {
		try {
			const data = await orgService.queryAll();
			setOrgTree(data);
		} catch (error) {
			message.error("获取组织机构数据失败");
		}
	};

	// 在组件加载时获取组织机构数据
	useEffect(() => {
		fetchOrgTree();
	}, []);

	// 递归构建树形选择器选项
	const buildTreeOptions = (data) => {
		return data.map((item) => ({
			value: item.id,
			label: item.name,
			children: item.children ? buildTreeOptions(item.children) : undefined,
		}));
	};

	useEffect(() => {
		fetchUserList();
	}, [queryParams]);

	const handlePageChange = (newPage: number, newPageSize: number) => {
		setQueryParams((prev) => ({
			...prev,
			page: newPage,
			pageSize: newPageSize,
		}));
	};

	const handleEdit = (user: UserInfo) => {
		setEditingUser(user);
		form.setFieldsValue(user);
		setDrawerVisible(true);
		setIsView(false);
	};

	/**
	 * 查看用户
	 * @param user 用户信息
	 */
	const handleView = (user: UserInfo) => {
		setEditingUser(user);
		form.setFieldsValue(user);
		setIsView(true);
		setDrawerVisible(true);
	};

	const handleSubmit = async (values) => {
		try {
			setLoading(true);
			if (editingUser) {
				await userService.update({ ...values, id: editingUser.id });
				message.success("更新用户成功");
			} else {
				await userService.add(values);
				message.success("创建用户成功");
			}
			setDrawerVisible(false);
			setEditingUser(null);
			form.resetFields();
			fetchUserList();
		} catch (error) {
			message.error(`${error.message}`);
		} finally {
			setLoading(false);
		}
	};

	const handleDrawerClose = () => {
		setDrawerVisible(false);
		setEditingUser(null);
		form.resetFields();
	};

	const handleAdd = () => {
		setEditingUser(null);
		form.resetFields();
		setDrawerVisible(true);
		setIsView(false);
	};

	//删除用户方法
	const handleDelete = async () => {
		try {
			setLoading(true);
			await userService.deleteUser(selectedRowKeys);
			message.success("删除用户成功");
			setSelectedRowKeys([]); // 清空选中项
			fetchUserList(); // 重新加载列表
		} catch (error) {
			message.error(`删除失败: ${error.message}`);
		} finally {
			setLoading(false);
		}
	};

	/**
	 * 修改密码
	 * @param values 密码
	 */
	const handleResetPassword = async (values: { password: string }) => {
		try {
			setLoading(true);
			const editUser: UserInfo = {
				id: selectedRowKeys[0],
				password: values.password,
			};

			await userService.editPwd(editUser);
			message.success("密码重置成功");
			setResetPasswordVisible(false);
			resetPasswordForm.resetFields();
		} catch (error) {
			message.error(`密码重置失败: ${error.message}`);
		} finally {
			setLoading(false);
		}
	};

	return (
		<>
			{/* 查询条件 */}
			<Card className="mb-4">
				<Form
					layout="inline"
					onFinish={(values) => {
						// 处理查询条件
						setQueryParams((prev) => ({
							...prev,
							...values,
							page: 1,
						}));
					}}
				>
					<Form.Item name="account" label="用户名">
						<Input placeholder="请输入用户名" allowClear />
					</Form.Item>
					<Form.Item name="name" label="姓名">
						<Input placeholder="请输入姓名" allowClear />
					</Form.Item>
					<Form.Item name="status" label="状态">
						<Select
							placeholder="请选择状态"
							options={[
								{ label: "启用", value: BasicStatus.ENABLE },
								{ label: "禁用", value: BasicStatus.DISABLE },
							]}
							allowClear
							style={{ width: 120 }}
						/>
					</Form.Item>
					<Form.Item>
						<Button type="primary" htmlType="submit">
							查询
						</Button>
						<Button
							className="ml-2"
							onClick={() => {
								// 重置查询条件
								setQueryParams({ page: 1, pageSize: 10 });
							}}
						>
							重置
						</Button>
					</Form.Item>
				</Form>
			</Card>
			<div className="h-4" />
			{/* 表格数据 */}
			<Card>
				<div className="flex justify-between mb-4">
					<div className="flex gap-2">
						<Button type="primary" onClick={handleAdd}>
							新增
						</Button>
						<Button danger disabled={selectedRowKeys.length === 0} onClick={handleDelete}>
							删除
						</Button>
						<Button type="dashed" disabled={selectedRowKeys.length !== 1} onClick={() => setResetPasswordVisible(true)}>
							重设密码
						</Button>
					</div>
					<TableToolbar
						onRefresh={() => setQueryParams((prev) => ({ ...prev }))}
						onSizeChange={setTableSize}
						columns={columns}
						selectedValues={selectedValues}
						onColumnChange={setSelectedValues}
					/>
				</div>
				<Table
					rowKey="id"
					size={tableSize}
					scroll={{ x: "max-content" }}
					loading={loading}
					pagination={{
						total,
						current: queryParams.page,
						pageSize: queryParams.pageSize,
						onChange: handlePageChange,
					}}
					columns={filteredColumns}
					dataSource={list}
					rowSelection={{
						type: "checkbox",
						selectedRowKeys: selectedRowKeys,
						onChange: (selectedKeys) => {
							setSelectedRowKeys(selectedKeys as string[]);
						},
					}}
				/>
			</Card>
			{/* 用户编辑页面 */}
			<Drawer
				title={editingUser ? "编辑用户" : "新增用户"}
				width={480}
				open={drawerVisible}
				onClose={handleDrawerClose}
				footer={
					<div className="flex justify-end gap-2">
						<Button onClick={handleDrawerClose}>取消</Button>
						{!isView && (
							<Button type="primary" onClick={() => form.submit()}>
								确定
							</Button>
						)}
					</div>
				}
			>
				<Form form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} onFinish={handleSubmit} disabled={isView}>
					<Form.Item name="account" label="账号" rules={[{ required: true, message: "请输入账号" }]}>
						<Input placeholder="请输入账号" disabled={editingUser !== null} />
					</Form.Item>

					<Form.Item name="name" label="姓名" rules={[{ required: true, message: "请输入姓名" }]}>
						<Input placeholder="请输入姓名" />
					</Form.Item>

					<Form.Item name="orgId" label="所属部门" rules={[{ required: true, message: "请选择所属部门" }]}>
						<TreeSelect
							placeholder="请选择所属部门"
							treeData={buildTreeOptions(orgTree)}
							treeDefaultExpandAll
							showSearch
							filterTreeNode={(input, node) => (node?.label ?? "").toLowerCase().includes(input.toLowerCase())}
						/>
					</Form.Item>

					<Form.Item name="gender" label="性别">
						<Select
							placeholder="请选择性别"
							options={[
								{ label: "男", value: "MALE" },
								{ label: "女", value: "FEMALE" },
							]}
						/>
					</Form.Item>

					<Form.Item
						name="phone"
						label="手机号"
						rules={[
							{ required: true, message: "请输入手机号" },
							{ pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号" },
						]}
					>
						<Input placeholder="请输入手机号" />
					</Form.Item>

					<Form.Item name="email" label="邮箱" rules={[{ type: "email", message: "请输入正确的邮箱格式" }]}>
						<Input placeholder="请输入邮箱" />
					</Form.Item>

					<Form.Item name="status" label="状态" initialValue={BasicStatus.ENABLE}>
						<Select
							options={[
								{ label: "启用", value: BasicStatus.ENABLE },
								{ label: "禁用", value: BasicStatus.DISABLE },
							]}
						/>
					</Form.Item>
				</Form>
			</Drawer>
			{/* 修改密码 */}
			<Drawer
				title="重置密码"
				width={380}
				open={resetPasswordVisible}
				onClose={() => {
					setResetPasswordVisible(false);
					resetPasswordForm.resetFields();
				}}
				footer={
					<div className="flex justify-end gap-2">
						<Button
							onClick={() => {
								setResetPasswordVisible(false);
								resetPasswordForm.resetFields();
							}}
						>
							取消
						</Button>
						<Button type="primary" onClick={() => resetPasswordForm.submit()}>
							确定
						</Button>
					</div>
				}
			>
				<Form
					form={resetPasswordForm}
					labelCol={{ span: 6 }}
					wrapperCol={{ span: 18 }}
					onFinish={handleResetPassword}
				>
					<Form.Item
						name="password"
						label="新密码"
						rules={[
							{ required: true, message: "请输入新密码" },
							{ min: 6, message: "密码长度不能小于6位" },
						]}
					>
						<Input.Password placeholder="请输入新密码" />
					</Form.Item>
					<Form.Item
						name="confirmPassword"
						label="确认密码"
						dependencies={["password"]}
						rules={[
							{ required: true, message: "请确认新密码" },
							({ getFieldValue }) => ({
								validator(_, value) {
									if (!value || getFieldValue("password") === value) {
										return Promise.resolve();
									}
									return Promise.reject(new Error("两次输入的密码不一致"));
								},
							}),
						]}
					>
						<Input.Password placeholder="请再次输入新密码" />
					</Form.Item>
				</Form>
			</Drawer>
		</>
	);
}
